package repository

import (
	"ruanGongKeShe16Zu/db"
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/service/vo"

	"gorm.io/gorm"
)

type IInstrumentRepository interface {
	Create(instrument *model.Instrument) (*model.Instrument, error)
	SelectById(id uint) (*model.Instrument, error)
	Update(instrument model.Instrument, newInstrument vo.InstrumentReq) (*model.Instrument, error)
	DeleteById(id uint) error
	InstrumentList(req *vo.ListInstrumentReq) ([]*model.Instrument, error)
}

type InstrumentRepository struct {
	DB *gorm.DB
}

func NewInstrumentRepository() IInstrumentRepository {
	return InstrumentRepository{DB: db.GetDB()}
}

func (o InstrumentRepository) Create(instrument *model.Instrument) (*model.Instrument, error) {
	if err := o.DB.Create(&instrument).Error; err != nil {
		return nil, err
	}
	return instrument, nil
}

func (o InstrumentRepository) SelectById(id uint) (*model.Instrument, error) {
	var instrument model.Instrument
	if err := o.DB.First(&instrument, id).Error; err != nil {
		return nil, err
	}
	return &instrument, nil
}

func (o InstrumentRepository) Update(instrument model.Instrument, newInstrument vo.InstrumentReq) (*model.Instrument, error) {
	if err := o.DB.Model(&instrument).Updates(newInstrument).Error; err != nil {
		return nil, err
	}
	return &instrument, nil
}

func (o InstrumentRepository) DeleteById(id uint) error {
	instrument, err := o.SelectById(id)
	if err != nil {
		return err
	}
	if err := o.DB.Delete(instrument).Error; err != nil {
		return err
	}
	return nil
}

func (o InstrumentRepository) InstrumentList(req *vo.ListInstrumentReq) ([]*model.Instrument, error) {
	if req.PageSize != 0 {
		var instruments []*model.Instrument
		if err := o.DB.Order("created_at desc").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&instruments).Error; err != nil {
			return nil, err
		}
		return instruments, nil
	}
	var instruments []*model.Instrument
	if err := o.DB.Find(&instruments).Error; err != nil {
		return nil, err
	}
	return instruments, nil
}
